package com.hyt.it.ogt.ks.job;

import java.time.Duration;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.hyt.it.ogt.ks.enums.PushCjStatusEnum;
import com.hyt.it.ogt.ks.model.cjvo.CjLogQueryParam;
import com.hyt.it.ogt.ks.model.entity.CjLog;
import com.hyt.it.ogt.ks.service.ICjLogService;
import com.hyt.it.ogt.ks.service.IThirdInterfaceService;
import com.hyt.it.ogt.ks.util.DateUtil;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;

import lombok.extern.slf4j.Slf4j;

/***
 * 推送成绩task
 * 
 * @author huangwu
 */
@Component
@Slf4j
public class CandidatePushCjTask {

	@Resource
	private ICjLogService cjLogService;

	@Resource
	private IThirdInterfaceService iThirdInterfaceService;

	// 处理考生考中状态
	@XxlJob("candidatePushCjTask")
	public void candidatePushCjTaskJob() {

		QueryTimeDto queryTimeDto = consQueryTimeDto();
		// 获取失败的数据
		List<CjLog> cjLogs = new ArrayList<>();
		boolean flag = true;
		Integer pageSize = 200;
		Integer pageNum = 1;
		CjLogQueryParam cjLogParems = new CjLogQueryParam();
		List<String> pushCjStatus = new ArrayList<>();
		pushCjStatus.add(PushCjStatusEnum.INIT.getStatus());
		pushCjStatus.add(PushCjStatusEnum.FAIL.getStatus());
		cjLogParems.setPushCjStatus(pushCjStatus);
		cjLogParems.setQueryStartTime(queryTimeDto.getStartTime());
		cjLogParems.setQueryEndTime(queryTimeDto.getEndTime());
		while (flag) {
			try {
				List<CjLog> cjLogsTemp = cjLogService.selectCjLogList(cjLogParems, pageNum, pageSize);
				if (CollectionUtils.isNotEmpty(cjLogsTemp)) {
					cjLogs.addAll(cjLogsTemp);
					pageNum++;
				} else {
					flag = false;
				}
			} catch (Exception e) {
				flag = false;
			}
		}

		if (CollectionUtils.isNotEmpty(cjLogs)) {
			for (CjLog cjLog : cjLogs) {
				log.info("开始二次考务推送成绩数据,apiLog：{}", JSON.toJSON(cjLog));
				// 策略，首先将加载到的初始化的数据计算是不是过去了10分钟，避免数据冲突
				if (PushCjStatusEnum.INIT.getStatus().equals(cjLog.getPushCjStatus())) {
					Boolean initDataAfterNowTenMins = initDataAfterNowTenMins(cjLog);
					if (!initDataAfterNowTenMins) {
						continue;
					}
				}
				// 把消息字符串转成对象
				try {
					Boolean result = iThirdInterfaceService.pushScoreToCj(cjLog.getExamId(), cjLog.getCandidateId(), null, cjLog);
					log.info("开始二次考务推送成绩数据 examid:{},candidateid:{},result:{}", cjLog.getExamId(), cjLog.getCandidateId(), result);
				} catch (Exception e) {
					log.error("开始二次考务推送成绩数据异常", e);
				}
			}
		}
	}

	private QueryTimeDto consQueryTimeDto() {
		QueryTimeDto queryTimeDto = new QueryTimeDto();
		// 获取参数
		log.info("二次处理考务推送成绩数据任务开始");
		String xxlparam = XxlJobHelper.getJobParam(); // 执行参数
		log.info("二次处理考务推送成绩数据任务开始xxlparam：{}", xxlparam);
		Date startTime = DateUtil.beforeOneHourToNowDate(new Date(), -24);
		Date endTime = new Date();
		String startTimeStr = "";
		String endTimeStr = "";
		try {
			if (StringUtils.isNotEmpty(xxlparam)) {
				String[] group = xxlparam.split("\\|");
				if (null != group && group.length > 1) {
					startTimeStr = group[0];
					endTimeStr = group[1];
				}
			}
		} catch (Exception e) {
			log.info("error", e);
		}

		if (StringUtils.isNotEmpty(startTimeStr)) {
			startTime = DateUtil.parseDate(startTimeStr);
		}
		if (StringUtils.isNotEmpty(endTimeStr)) {
			endTime = DateUtil.parseDate(endTimeStr);
		}
		queryTimeDto.setStartTime(startTime);
		queryTimeDto.setEndTime(endTime);
		return queryTimeDto;
	}

	/****
	 * 判断初始化的数据是不是已经过去10分钟了
	 * 
	 * @param cjLog
	 * @return
	 */
	private Boolean initDataAfterNowTenMins(CjLog cjLog) {
		if (!PushCjStatusEnum.INIT.getStatus().equals(cjLog.getPushCjStatus())) {
			return true;
		}
		LocalDateTime createDate = cjLog.getCreateDate();
		LocalDateTime nowTime = LocalDateTime.now();
		Duration duration = Duration.between(createDate, nowTime);
		long minutes = duration.toMinutes();// 相差的分钟数
		if (minutes > 10) {
			return true;
		}
		return false;
	}

	
	class QueryTimeDto {
		private Date startTime;
		private Date endTime;

		public Date getStartTime() {
			return startTime;
		}

		public void setStartTime(Date startTime) {
			this.startTime = startTime;
		}

		public Date getEndTime() {
			return endTime;
		}

		public void setEndTime(Date endTime) {
			this.endTime = endTime;
		}
	}

}
